package demo.android.myapplication.demos.touch

import android.content.Context
import android.graphics.Canvas
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PointF
import android.util.AttributeSet
import android.util.SparseArray
import android.view.MotionEvent
import android.view.MotionEvent.*
import android.view.View
import androidx.core.util.forEach
import cn.android.basic.decodeBitmap
import cn.android.basic.dp
import cn.android.basic.int
import demo.android.myapplication.R

/**
 * Created by guoshiwen on 2021/7/27.
 */
class MultiPointView3 @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val paint = Paint(Paint.ANTI_ALIAS_FLAG).apply {
        style = Paint.Style.STROKE
        strokeJoin = Paint.Join.ROUND
        strokeCap = Paint.Cap.ROUND
        strokeWidth = 3.dp
    }
    private val paths = SparseArray<Path>()

    override fun onDraw(canvas: Canvas) {
        paths.forEach { _, path ->
            canvas.drawPath(path, paint)
        }
    }

    override fun onTouchEvent(event: MotionEvent): Boolean {
        when(event.actionMasked) {
            ACTION_DOWN, ACTION_POINTER_DOWN -> event.run{
                val path = Path()
                path.moveTo(getX(actionIndex), getY(actionIndex))
                paths.put(getPointerId(actionIndex), path)
            }
            ACTION_MOVE -> event.run {
                for (i in 0 until event.pointerCount) {
                    paths[event.getPointerId(i)]
                        .lineTo(event.getX(i), event.getY(i))
                }
                invalidate()
            }
            ACTION_POINTER_UP, ACTION_UP -> event.run {
                paths.remove(getPointerId(actionIndex))
                invalidate()
            }
        }
        return true
    }
}